package it.polimi.traveldream.ejb;

import it.polimi.traveldream.dto.DefaultPackageDTO;
import it.polimi.traveldream.dto.DetailedDefaultPackageDTO;
import it.polimi.traveldream.entity.DefaultPackage;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Stateless
public class DefaultPackageManagerBean implements DefaultPackageManager {

	@PersistenceContext
	private EntityManager em;

	@Override
	public void save(DetailedDefaultPackageDTO pack) {
		if (pack.getId() == null) {
			this.em.persist(new DefaultPackage(pack));
		} else {
			this.em.merge(new DefaultPackage(pack));
		}
	}

	@Override
	public List<DefaultPackageDTO> getPackages() {
		List<DefaultPackageDTO> list = new ArrayList<>();
		List<DefaultPackage> packages = this.em.createNamedQuery(DefaultPackage.FIND_ALL,
				DefaultPackage.class).getResultList();
		for (DefaultPackage pack : packages) {
			list.add(pack.convertToDTO());
		}
		return list;
	}

	@Override
	public DetailedDefaultPackageDTO findPackage(Integer id) {
		return this.em.find(DefaultPackage.class, id).convertToDetailedDTO();
	}
}
